<template>
  <div v-loading="isLoading">
    <div class="searchBar">
      <el-form :inline="true">
        <el-form-item>
          <el-input
            placeholder="请输入关键字"
            v-model="searchForm.keyword"
            size="mini"
          />
        </el-form-item>

        <el-form-item>
          <el-button size="mini" type="primary" @click="listData()"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-button
      style="margin-top: 1em"
      type="text"
      class="right-button"
      @click="showAdd()"
      >添加数据</el-button
    >
    <el-table
      :data="pageData.record"
      stripe
      style="width: 100%"
      border
      :default-sort="{ prop: 'id', order: 'ascending' }"
    >
      <el-table-column prop="id" sortable label="id" width="80" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column id="logo" label="logo" width="110" style="padding: 0px">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" width="100px" />
        </template>
      </el-table-column>
      <el-table-column
        prop="description"
        label="分类描述"
        show-overflow-tooltip
      />
      <el-table-column
        prop="articleNum"
        sortable
        label="帖子数量"
        width="110"
      />
      <el-table-column prop="createUserNickname" label="创建人" width="100" />
      <el-table-column prop="createTime" sortable label="创建时间" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="showDesc(scope.row)" type="text" size="small"
            >查看</el-button
          >
          <el-button
            @click.stop="showEdit(scope.row, 2)"
            type="text"
            size="small"
            >编辑</el-button
          >
          <el-button
            type="text"
            style="color: #f56c6c"
            size="small"
            @click.stop="del(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :page-sizes="[10, 15, 20]"
        :page-size="pageData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="新增分类"
      :visible.sync="isAdd"
      v-loading="isLoading"
      width="30%"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="6em"
        class="addForm"
        label-position="left"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input type="textarea" v-model="addForm.description"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload
            class="avatar-uploader"
            :http-request="uploadImage"
            action="http:localhost:8081/admin/category/uploadAvatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="addForm.avatar" :src="addForm.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button
            v-loading="isUpload"
            type="primary"
            @click="submitForm('addForm')"
          >
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { Message } from "element-ui";
export default {
  name: "categoryPage",
  data() {
    return {
      searchForm: {
        keyword: "",
        current: 1,
        size: 10,
      },
      isAdd: false,
      addForm: {
        name: "",
        description: "",
        avatar: "",
      },
      isUpload: false,
      addConfig: {},
      pageData: [],
      isLoading: true,
      isShowDesc: false,
      isEdit: false,
      loginUser: {},
      rules: {
        name: [{ required: true, message: "请输入分类", trigger: "blur" }],
      },
    };
  },
  methods: {
    listData() {
      this.isLoading = true;
      this.postRequest("/category/list", this.searchForm).then((res) => {
        this.pageData = res.data.data;
        this.isLoading = false;
      });
    },
    showDesc(row) {
      // this.isShowDesc = true;
      console.log(row);
    },
    isEmptyStr(s) {
      if (typeof s == "string" && s.length > 0) {
        return false;
      }
      return true;
    },
    isNotTrim(str) {
      if (str.indexOf(" ") == -1) {
        return false;
      }
      return true;
    },
    showEdit(item) {
      this.addForm = item;
      this.isAdd = true;
    },
    showAdd() {
      if (this.addForm.id != undefined) {
        this.addForm = {
          name: "",
          description: "",
          avatar: "",
        };
      }
      this.isAdd = true;
    },
    submitForm(formName) {
      this.isLoading = true;

      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.postRequest("/admin/category/save", this.addForm).then((res) => {
          if (res.data.status == 200) {
            Message({
              message: "保存成功",
              type: "success",
            });
          }
          this.listData();
        });
        this.isAdd = false;
        this.isLoading = false;
      });
    },
    del(id) {
      this.deleteRequest(`/admin/category/delete/${id}`).then((res) => {
        if (res.data.status == 200) {
          Message({
            message: "删除成功",
            type: "success",
          });
        }
        this.listData();
      });
    },
    handleAvatarSuccess(res, file) {
      this.addForm.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const flag = file.type === "image/jpeg" || file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!flag) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt20M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      return flag;
    },
    uploadImage(file) {
      this.isUpload = true;
      var formData = new FormData();
      formData.append("file", file.file);
      var requestConfig = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      this.postRequest(
        "/admin/category/uploadAvatar",
        formData,
        requestConfig
      ).then((res) => {
        if (res.status == 200 && res.data.status == 200) {
          this.$message({
            showClose: true,
            message: "文件上传成功",
            type: "success",
          });
          this.addForm.avatar = res.data.data;
        }
        this.isUpload = false;
      });
    },
    currentChange(current) {
      this.searchForm.current = current;
      this.listData();
    },
    sizeChange(size) {
      this.searchForm.size = size;
      this.listData();
    },
  },
  created() {
    this.loginUser = JSON.parse(localStorage.getItem("loginUser"));
    this.listData();
  },
};
</script>
<style scope>
.addForm {
  width: 80%;
  margin: auto;
}
#logo {
  padding: 0 !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
